package com.ssy.lingxi.enhance.serviceimpl.process;

import com.querydsl.core.BooleanBuilder;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.enhance.constant.*;
import com.ssy.lingxi.enhance.entity.*;
import com.ssy.lingxi.enhance.handler.async.MessageAsyncService;
import com.ssy.lingxi.enhance.handler.async.ReportAsyncService;
import com.ssy.lingxi.enhance.handler.jpa.QueryDslUtil;
import com.ssy.lingxi.enhance.model.dto.ConfirmAllReceiptDTO;
import com.ssy.lingxi.enhance.model.dto.ConfirmReceiveDeliverReceiptDTO;
import com.ssy.lingxi.enhance.model.qo.ProduceNoticeOrderQO;
import com.ssy.lingxi.enhance.model.vo.ProduceNoticeOrderListVO;
import com.ssy.lingxi.enhance.repository.InnerWorkflowRecordRepository;
import com.ssy.lingxi.enhance.repository.OuterWorkflowRecordRepository;
import com.ssy.lingxi.enhance.repository.PNOReceiveDeliverDetailRepository;
import com.ssy.lingxi.enhance.repository.ProduceNoticeOrderRepository;
import com.ssy.lingxi.enhance.service.process.ProcessToBeConfirmReceiptService;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.report.api.enums.EnhanceProcessOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.workflow.api.feign.ProcessFeign;
import com.ssy.lingxi.workflow.api.model.contant.ProcessTaskStatusEnum;
import com.ssy.lingxi.workflow.api.model.vo.request.TaskExecuteVO;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 加工能力 - 确认生产通知单(加工企业) - 待确认回单生产通知单 - 业务实现层
 * @author fhj
 * @date 2020/10/20
 * @version 2.0.0
 */
@Slf4j
@Service
public class ProcessToBeConfirmReceiptServiceImpl implements ProcessToBeConfirmReceiptService {

    @Resource
    private ProcessFeign processFeign;
    @Resource
    private QueryDslUtil queryDslUtil;
    @Resource
    private ProduceNoticeOrderRepository produceNoticeOrderRepository;
    @Resource
    private PNOReceiveDeliverDetailRepository pnoReceiveDeliverDetailRepository;
    @Resource
    private InnerWorkflowRecordRepository innerWorkflowRecordRepository;
    @Resource
    private OuterWorkflowRecordRepository outerWorkflowRecordRepository;
    @Resource
    private ReportAsyncService reportAsyncService;
    @Resource
    private MessageAsyncService messageAsyncService;

    /**
     * 列表
     * */
    @Override
    public Wrapper<PageData<ProduceNoticeOrderListVO>> list(ProduceNoticeOrderQO qo, UserLoginCacheDTO user) {
        //查询表实体 - 生产通知单
        QProduceNoticeOrderDO pno = QProduceNoticeOrderDO.produceNoticeOrderDO;

        //查询条件构造 - 必要条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(pno.processMemberId.eq(user.getMemberId()));
        predicates.and(pno.processRoleId.eq(user.getMemberRoleId()));
        predicates.and(pno.outerStatus.eq(PNOOuterStatusEnum.TO_BE_CONFIRM_RECEIPT.getCode()));
        predicates.and(pno.status.eq(PNOAllStatusEnum.TO_BE_PROCESS_CONFIRM_RECEIPT.getCode()));

        return Wrapper.success(queryDslUtil.getProcessPNOList(qo, pno, predicates));
    }

    /**
     * 确认回单
     * */
    @Override
    @Transactional
    public Wrapper<Void> confirmReceipt(ConfirmReceiveDeliverReceiptDTO dto, UserLoginCacheDTO user) {
        //根据ID获取生产通知单详情
        ProduceNoticeOrderDO produceNoticeOrder = produceNoticeOrderRepository.findById(dto.getProduceNoticeOrderId()).orElse(null);
        if(produceNoticeOrder == null) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(!produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.TO_BE_PROCESS_CONFIRM_RECEIPT.getCode())) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_OPERATION_INNER_STATUS_AS_TO_BE_PROCESS_CONFIRM_RECEIPT);
        }

        //根据ID获取生产通知单收发货明细详情
        PNOReceiveDeliverDetailDO pnoReceiveDeliverDetail = pnoReceiveDeliverDetailRepository.findById(dto.getPnoReceiveDeliverDetailId()).orElse(null);
        if(pnoReceiveDeliverDetail == null) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(!pnoReceiveDeliverDetail.getReceiptStatus().equals(ReceiptStatusEnum.TO_BE_CONFIRM_RECEIPT.getCode())) {
            return Wrapper.fail(ResponseCode.ENHANCE_PNO_RECEIVE_DELIVER_DETAIL_MUST_BE_TO_BE_CONFIRM_RECEIPT);
        }

        //更新生产通知单收发货明细：回单状态
        pnoReceiveDeliverDetail.setReceiptStatus(ReceiptStatusEnum.ALREADY_CONFIRM_RECEIPT.getCode());
        pnoReceiveDeliverDetailRepository.saveAndFlush(pnoReceiveDeliverDetail);

        //记录外部工作流记录
        OuterWorkflowRecordDO outerWorkflowRecordDO = new OuterWorkflowRecordDO();
        outerWorkflowRecordDO.setProduceNoticeOrderId(produceNoticeOrder.getId());
        outerWorkflowRecordDO.setUserId(user.getUserId());
        outerWorkflowRecordDO.setMemberId(user.getMemberId());
        outerWorkflowRecordDO.setRoleId(user.getMemberRoleId());
        outerWorkflowRecordDO.setStep(produceNoticeOrder.getOuterStatus());
        outerWorkflowRecordDO.setRoleName(user.getMemberRoleName());
        outerWorkflowRecordDO.setStatus("已完成通知单");
        outerWorkflowRecordDO.setOperate("确认回单");
        outerWorkflowRecordDO.setOperateTime(System.currentTimeMillis());
        outerWorkflowRecordDO.setOpinion("确认回单");
        outerWorkflowRecordRepository.saveAndFlush(outerWorkflowRecordDO);

        //记录加工企业内部工作流记录
        InnerWorkflowRecordDO innerWorkflowRecord = new InnerWorkflowRecordDO();
        innerWorkflowRecord.setProduceNoticeOrderId(produceNoticeOrder.getId());
        innerWorkflowRecord.setUserId(user.getUserId());
        innerWorkflowRecord.setMemberId(user.getMemberId());
        innerWorkflowRecord.setRoleId(user.getMemberRoleId());
        innerWorkflowRecord.setType(RoleTypeEnum.PROCESS.getCode());
        innerWorkflowRecord.setStep(produceNoticeOrder.getStatus());
        innerWorkflowRecord.setOperator(user.getUserName());
        innerWorkflowRecord.setDepartment(user.getUserOrgName());
        innerWorkflowRecord.setJobTitle(user.getUserJobTitle());
        innerWorkflowRecord.setStatus("已确认回单");
        innerWorkflowRecord.setOperate("确认回单");
        innerWorkflowRecord.setOperateTime(System.currentTimeMillis());
        innerWorkflowRecord.setOpinion("确认回单");
        innerWorkflowRecordRepository.saveAndFlush(innerWorkflowRecord);

        return Wrapper.success();
    }

    /**
     * 确认本单全部发货单已收到回单
     * */
    @Override
    @Transactional
    public Wrapper<Void> confirmAllReceipt(ConfirmAllReceiptDTO dto, UserLoginCacheDTO user) {
        //根据ID获取生产通知单详情
        ProduceNoticeOrderDO produceNoticeOrder = produceNoticeOrderRepository.findById(dto.getProduceNoticeOrderId()).orElse(null);
        if(produceNoticeOrder == null) {
            return Wrapper.fail(ResponseCode.ENHANCE_BY_ID_NOT_FOUND_PNO);
        }
        if(!produceNoticeOrder.getStatus().equals(PNOAllStatusEnum.TO_BE_PROCESS_CONFIRM_RECEIPT.getCode())) {
            return Wrapper.fail(ResponseCode.ENHANCE_ONLY_OPERATION_INNER_STATUS_AS_TO_BE_PROCESS_CONFIRM_RECEIPT);
        }

        //调用工作流服务 -> 执行外部流程
        TaskExecuteVO taskExecuteVO = new TaskExecuteVO();
        taskExecuteVO.setMemberId(produceNoticeOrder.getSupplierMemberId());
        taskExecuteVO.setRoleId(produceNoticeOrder.getSupplierRoleId());
        taskExecuteVO.setDataId(produceNoticeOrder.getId());
        taskExecuteVO.setTaskId(produceNoticeOrder.getOuterTaskId());
        taskExecuteVO.setAgree(dto.getStatus() ? ProcessTaskStatusEnum.AGREE.getCode() : ProcessTaskStatusEnum.DISAGREE.getCode());
        taskExecuteVO.setProcessKey(produceNoticeOrder.getOuterProcessKey());
        Wrapper<SimpleTaskCompleteVO> outerWrapper = processFeign.completeSimpleTask(taskExecuteVO);
        if(ResponseCode.SUCCESS.getCode() == outerWrapper.getCode()) {
            //更新生产通知单：外部状态、外部任务ID、状态、供应商内部状态、加工企业内部状态
            produceNoticeOrder.setOuterStatus(outerWrapper.getData().getStatus());
            produceNoticeOrder.setOuterTaskId(outerWrapper.getData().getTaskId());
            produceNoticeOrder.setStatus(dto.getStatus() ? PNOAllStatusEnum.COMPLETE.getCode() : PNOAllStatusEnum.TO_BE_PROCESS_ADD_DELIVERY.getCode());
            produceNoticeOrder.setSupplierInnerStatus(dto.getStatus() ? PNOSupplierInnerStatusEnum.ALREADY_COMPLETE.getCode() : PNOSupplierInnerStatusEnum.ALREADY_SUBMIT.getCode());
            produceNoticeOrder.setProcessInnerStatus(dto.getStatus() ? PNOProcessInnerStatusEnum.ALREADY_COMPLETE.getCode() : PNOProcessInnerStatusEnum.TO_BE_ADD_DELIVERY.getCode());
            produceNoticeOrderRepository.saveAndFlush(produceNoticeOrder);
        }else {
            log.error("工作流服务异常:" + outerWrapper.getMessage());
            throw new BusinessException(ResponseCode.ENHANCE_WORKFLOW_ERROR);
        }

        //调用报表服务、消息服务 -> 确认全部收到回单：新增操作通知。继续发货：新增操作通知、发送系统消息（如果调用过程出现异常, 无需回滚, 直接catch打印日志正常返回。）
        if(dto.getStatus()) {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_PROCESS.getCode(),
                    null,  null,
                    EnhanceProcessOperateTypeEnum.TO_BE_CONFIRM_RECEIPT.getCode(), 1L
            );
        }else {
            reportAsyncService.addOperateNotice(
                    user.getMemberId(), user.getMemberRoleId(), OperateDataSourceEnum.ENHANCE_PROCESS.getCode(),
                    EnhanceProcessOperateTypeEnum.TO_BE_ADD_DELIVERY.getCode(),  1L,
                    EnhanceProcessOperateTypeEnum.TO_BE_CONFIRM_RECEIPT.getCode(), 1L
            );
            messageAsyncService.sendSystemMessage(user.getMemberId(), user.getMemberRoleId(),
                    MessageTemplateCode.production_order_handle_process_shipment, Stream.of(produceNoticeOrder.getNoticeNo(), produceNoticeOrder.getSummary()).collect(Collectors.toList())
            );
        }

        return Wrapper.success();
    }
}
